package com.doit.day02;


import com.alibaba.fastjson.JSON;

import java.sql.*;
import java.util.Iterator;

//需求:读取mysql数据库中的一张表，要求每次调用迭代器都返回表中的一行数据，返回一个json串
public class MysqlIterator implements Iterator<String> {
    private ResultSet resultSet;

    public MysqlIterator() throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        PreparedStatement pps = conn.prepareStatement("select * from user_info");
        resultSet = pps.executeQuery();
    }

    @Override
    public boolean hasNext() {
        boolean flag =true;
        try {
            flag =  resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public String next() {
        String jsonString = "";

        try {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");
            String gender = resultSet.getString("gender");
            UserInfo userInfo = new UserInfo(id, name, age, gender);
            jsonString = JSON.toJSONString(userInfo);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

}
